package com.cy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.common.Constant;
import com.cy.entity.Comment;
import com.cy.entity.DiscussPost;
import com.cy.entity.Event;
import com.cy.entity.User;
import com.cy.event.EventProducer;
import com.cy.service.CommentService;
import com.cy.service.DiscussPostService;
import com.cy.service.LikeService;
import com.cy.service.UserService;
import com.cy.util.CommunityUtil;
import com.cy.util.HostHolder;
import com.cy.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.ReaderEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

import static com.cy.common.Constant.ENTITY_TYPE_COMMENT;

/**
 * <p>
 *  帖子
 * </p>
 *
 * @author cy
 * @since 2021-11-08
 */
@Controller
@RequestMapping("/discuss-post")
public class DiscussPostController {

    @Autowired
    private DiscussPostService discussPostService;

    @Resource
    private HostHolder hostHolder;
    @Resource
    private UserService userService;

    @Resource
    private CommentService commentService;

    @Resource
    private LikeService likeService;

    @Resource
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/findByPage")
    public Page<DiscussPost> findByPage(){
        Page<DiscussPost> discussPostPage = discussPostService.findByPage(1, 10, 0);
        return discussPostPage;
    }

    @PostMapping(path = "/add")
    @ResponseBody
    public String addDiscussPort(String title, String content){
        User user = hostHolder.getUser();
        if(user == null){
            return CommunityUtil.getJsonString(403, "你还没有登录！");
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setStatus(0);
        post.setType(0);
        post.setCreateTime(new Date());
        discussPostService.addDiscussPost(post);

        // 触发发帖事件,发布帖子时将帖子添加到消息队列，然后消费者再将消息队列中帖子添加到elasticsearch
        Event event = new Event();
        event.setTopic(Constant.TOPIC_PUBLIC);
        event.setUserId(user.getId());
        event.setEntityType(Constant.ENTITY_TYPE_POST);
        event.setEntityId(post.getId());
        eventProducer.fireMessage(event);

        // 计算帖子分数
        redisTemplate.opsForSet().add(RedisKeyUtil.getPostScoreKey(), post.getId());

        // 报错的情况,将来统一处理
        return CommunityUtil.getJsonString(0, "发布成功！");
    }


    @RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page<Comment> page) {
        // 帖子
        DiscussPost post = discussPostService.getById(discussPostId);
        model.addAttribute("post", post);
        // 作者
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user", user);

        //帖子点赞数
        long likeCount = likeService.findEntityLikeCount(Constant.ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);
        //帖子点赞状态
        int likeStatus = hostHolder.getUser() == null ? 0 :
                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), Constant.ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);

        // 评论分页信息
        page.setSize(5);
        model.addAttribute("path", "/discuss-post/detail/" + discussPostId);

        // 评论: 给帖子的评论
        // 回复: 给评论的评论
        // 评论列表
        QueryWrapper<Comment> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("entity_type", Constant.ENTITY_TYPE_POST)
                        .eq("entity_id", post.getId());
        Page<Comment> commentList = commentService.page(page, wrapper1);
        // 评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList.getRecords()) {
                // 评论VO
                Map<String, Object> commentVo = new HashMap<>();
                // 评论
                commentVo.put("comment", comment);
                // 作者
                commentVo.put("user", userService.findUserById(comment.getUserId()));

                //评论点赞数
                likeCount = likeService.findEntityLikeCount( ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                //评论点赞状态
                likeStatus = hostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                // 回复列表
                QueryWrapper<Comment> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("entity_type", ENTITY_TYPE_COMMENT)
                                .eq("entity_id", comment.getId());
                List<Comment> replyList = commentService.list(wrapper2);
                // 回复VO列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        // 回复
                        replyVo.put("reply", reply);
                        // 作者
                        replyVo.put("user", userService.findUserById(reply.getUserId()));
                        // 回复目标
                        User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);

                        //回复点赞数
                        likeCount = likeService.findEntityLikeCount( ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        //回复点赞状态
                        likeStatus = hostHolder.getUser().getId() == null ? 0 :
                                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);

                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);

                // 回复数量
                int replyCount = commentService.count(wrapper2);
                commentVo.put("replyCount", replyCount);

                commentVoList.add(commentVo);
            }
        }

        model.addAttribute("comments", commentVoList);

        return "/site/discuss-detail";
    }



    // 置顶
    @PostMapping(path = "/top")
    @ResponseBody
    public String setTop(int id){
        discussPostService.updateType(id, 1);

        // 因为这里帖子的类型发生了改变所有elasticsearch中也需改变帖子类型
        // 触发发帖事件,发布帖子时将帖子添加到消息队列，然后消费者再将消息队列中帖子添加到elasticsearch
        Event event = new Event();
        event.setTopic(Constant.TOPIC_PUBLIC);
        event.setUserId(hostHolder.getUser().getId());
        event.setEntityType(Constant.ENTITY_TYPE_POST);
        event.setEntityId(id);
        eventProducer.fireMessage(event);

        return CommunityUtil.getJsonString(0);
    }


    // 加精
    @PostMapping(path = "/wonderful")
    @ResponseBody
    public String setWonderful(int id){
        discussPostService.updateStatus(id, 1);

        // 因为这里帖子的状态发生了改变所有elasticsearch中也需改变帖子类型
        // 触发发帖事件,发布帖子时将帖子添加到消息队列，然后消费者再将消息队列中帖子添加到elasticsearch
        Event event = new Event();
        event.setTopic(Constant.TOPIC_PUBLIC);
        event.setUserId(hostHolder.getUser().getId());
        event.setEntityType(Constant.ENTITY_TYPE_POST);
        event.setEntityId(id);
        eventProducer.fireMessage(event);

        // 计算帖子分数
        redisTemplate.opsForSet().add(RedisKeyUtil.getPostScoreKey(), id);

        return CommunityUtil.getJsonString(0);
    }

    // 删除
    @PostMapping(path = "/delete")
    @ResponseBody
    public String setDelete(int id){
        discussPostService.updateStatus(id, 2);   // 2拉黑

        // 将帖子从el中删除
        Event event = new Event();
        event.setTopic(Constant.TOPIC_DELETE);
        event.setUserId(hostHolder.getUser().getId());
        event.setEntityType(Constant.ENTITY_TYPE_POST);
        event.setEntityId(id);
        eventProducer.fireMessage(event);

        return CommunityUtil.getJsonString(0);
    }



}
